#include<iostream>
using namespace std;
#include<unistd.h>
#include<string>
#include<sys/types.h>
#include<sys/wait.h>
#include<fcntl.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<errno.h>
#include<cstring>

#define NUM_KEY 0x66
#define PATH "."
#define MAX_SIZE 4096


key_t getkey(){
    key_t k = ftok(PATH,NUM_KEY);
    if(k < 0){
        cerr<<errno<<"string err:"<<strerror(errno)<<endl;
        exit(1);
    }
    return k;
}


int creatshm(key_t k){
    int ret = shmget(k,MAX_SIZE,IPC_CREAT | IPC_EXCL|0666);//创建成功返回初始地址
    if(ret < 0){
        cerr<<errno<<"string err:"<<strerror(errno)<<endl;
        exit(2);
    }
    return ret;

}

int getshm(key_t k){
    int ret = shmget(k,MAX_SIZE,IPC_CREAT);
    if(ret < 0){
        cerr<<errno<<"string err:"<<strerror(errno)<<endl;
        exit(3);
    }
    return ret;
    
}


void delshm(int shmid){
    int ret = shmctl(shmid,IPC_RMID,nullptr);
    if(ret < 0){
        cerr<<errno<<"string err:"<<strerror(errno)<<endl;
        exit(4);
    }
}

void* attachshm(int shmid){
    void* ret = shmat(shmid,nullptr,0);
    if((long int)ret == -1){
        cerr<<errno<<"string err:"<<strerror(errno)<<endl;
        exit(5);
    }
    return ret;
}

void unlink_shm(void* start){
    int ret = shmdt(start);
    if(ret < 0){
        cerr<<errno<<"string err:"<<strerror(errno)<<endl;
        exit(6);
    }
}
